package com.tdly.buduizhong.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tdly.buduizhong.R;
import com.tdly.buduizhong.base.BaseActivity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class HistoryActivity extends BaseActivity implements View.OnClickListener ,AdapterView.OnItemClickListener{
    private Context context = this;
    private RelativeLayout ll_btn;
    private TextView tv_load_title, tv_load_edit,iv_tv_item;
    private Button bt_load_delete, bt_load_select;
    private ListView lv;
    private ImageView iv_load_nodata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        initView();
    }

    private void initView() {
        tv_load_title = findViewById(R.id.tv_load_title);
        tv_load_edit = findViewById(R.id.tv_load_edit);
        ll_btn = findViewById(R.id.ll_btn);
        bt_load_delete = findViewById(R.id.bt_load_delete);
        bt_load_select = findViewById(R.id.bt_load_select);
        lv = findViewById(R.id.lv);
        iv_tv_item=findViewById(R.id.tv_item);
        iv_load_nodata = findViewById(R.id.iv_load_nodata);
        try {
            String path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/tdly/";
            getFiles(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        lv.setOnItemClickListener(this);
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {//长按删除
            @Override
            public boolean onItemLongClick(AdapterView<?> parent,  View view,  int position, long id) {
                final String text = (String) ((TextView)view.findViewById(R.id.tv_item)).getText();
                //定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setMessage("确定删除?");
                builder.setTitle("提示");

                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            // 找到文件所在的路径并删除该文件
                            File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/tdly/", text);
                            file.delete();
                            Toast.makeText(context,text+" 删除成功",Toast.LENGTH_SHORT).show();
                            try {
                                String path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/tdly/";
                                getFiles(path);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new AlertDialog.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.create().show();
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.tv_setting:
                break;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //通过view获取其内部的组件，进而进行操作
        String text = (String) ((TextView)view.findViewById(R.id.tv_item)).getText();
        //大多数情况下，position和id相同，并且都从0开始
        FileInputStream fileInputStream=null;
        BufferedReader reader_mes=null;
        StringBuffer buffer_mes=new StringBuffer();

        try {

            File Folder = new File(Environment.getExternalStorageDirectory().getCanonicalPath(), "tdly");
            if (!Folder.exists())//判断文件夹是否存在，不存在则创建文件夹，已经存在则跳过
            {

                Folder.mkdir();//创建文件夹

                //两种方式判断文件夹是否创建成功
                //Folder.isDirectory()返回True表示文件路径是对的，即文件创建成功，false则相反
                boolean isFilemaked1 = Folder.isDirectory();
                //Folder.mkdirs()返回true即文件创建成功，false则相反
                boolean isFilemaked2 = Folder.mkdirs();

                if (isFilemaked1 || isFilemaked2) {
                    Log.i("123123","创建文件夹成功");
                } else {
                    Log.i("123123","创建文件夹失败");
                }

            }else {
                Log.i("123123","文件夹已存在");
            }

            String path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/tdly/";
            File file = new File(path,text);
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int len = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = fis.read(b)) != -1) {
                baos.write(b, 0, len);
            }
            byte[] data = baos.toByteArray();
            baos.close();
            fis.close();
            buffer_mes.append(new String(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String tmp=new String(buffer_mes);
       // String[] tmp =t.split("\t");
        Intent intent1=new  Intent(HistoryActivity.this, HomeActivity.class).putExtra("tmp", tmp).putExtra("name",text);
        //标识列 + Intent
        setResult(10, intent1);
        finish();
        //Toast.makeText(this, buffer_mes, Toast.LENGTH_SHORT).show();
    }

    //定义读取文件的方法:
    public void getFiles(String path) throws IOException {
        ArrayList<String> data =new ArrayList<>();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            ArrayList<File> fileList = new ArrayList<File>();
            File file = new File(path);
            if(file.isDirectory()){
                File []files = file.listFiles();
                for(File fileIndex:files){
                    if(fileIndex.isDirectory()){
                        getFiles(fileIndex.getPath());
                    }else{
                        fileList.add(fileIndex);
                        data.add(fileIndex.getName());
                        Log.e("wenjian",fileIndex.getName());
                    }
                }
            }
            if(fileList.size()==0){
                iv_load_nodata.setVisibility(View.VISIBLE);
            }else{
                lv.setAdapter(new ViewHolderAdapter(context,data));
            }
        }
    }

    public class ViewHolderAdapter extends BaseAdapter
    {
        private List<String> mData;
        private LayoutInflater mInflater;

        public ViewHolderAdapter(Context context, List<String> data)
        {
            mData = data;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            return mData.size();
        }

        @Override
        public Object getItem(int position)
        {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ViewHolder holder = null;
            // 判断是否缓存
            if (convertView == null)
            {
                holder = new ViewHolder();
                // 通过LayoutInflater实例化布局
                convertView = mInflater.inflate(R.layout.list_item, null);
                holder.mTitle = (TextView) convertView.findViewById(R.id.tv_item);
                holder.mImgView = (ImageView) convertView.findViewById(R.id.iv_item_load);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

//            holder.mImgView.setBackgroundResource(R.mipmap.ic_launcher);
            holder.mTitle.setText(mData.get(position));

            return convertView;
        }

        public final class ViewHolder
        {
            public TextView mTitle;
            public ImageView mImgView;
        }
    }
}